package com.firefightingiot.firefightingiot.web.service;

import org.junit.Test;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;

/**
 * 继承Application接口后项目启动时会按照执行顺序执行run方法
 * 通过设置Order的value来指定执行的顺序
 */
@Component
public class UDPClient {

    /**
     * UDP客服端
     * @throws IOException
     */
    public ArrayList startClient(String ss) throws IOException, InterruptedException {
        ArrayList arrayList = new ArrayList();
        // 1.定义服务器的地址、端口号、数据
        //服务器ip
        InetAddress address = InetAddress.getByName("122.4.227.102");
        //服务器port
        int port = 21111;
        byte[] data = hexStringToBytes(ss);
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        //绑定客户端端口
        DatagramSocket socketSender = new DatagramSocket(null);
        try {
            InetSocketAddress addr = new InetSocketAddress(address, 45670);
            socketSender.bind(addr);
            socketSender.send(packet);
            //设置超时时间
            socketSender.setSoTimeout(2000);

            byte[] data2 = new byte[1024];
            DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
            //2.接收服务器响应的数据
            //循环接收数据
            while (true) {
                socketSender.receive(packet2);
                //3.读取数据
                String reply = bytesToHexString(data2, packet2.getLength());
                System.out.println("服务器说:" + reply);
                arrayList.add(reply);
                /*//判断是否为文件上传命令
                if (ss.substring(24, 26).equals("0F") || ss.substring(24, 26).equals("0f")) {

                }*/
                String cmd = reply.substring(24, 26);
                String para = reply.substring(36, 38);
                //判断文件上传命令的应答帧是否包含文件编号id
                if (cmd.equals("85") && para.equals("02")) {
                    //4.关闭资源
                    socketSender.close();
                    break;
                }

            }
            socketSender.close();
        } catch (Exception e) {
            System.out.println(e);
            System.out.printf("连接超时", e);
        } finally {
            socketSender.close();
        }
        return arrayList;
    }
        public void startClient1(String data) throws IOException {
            DatagramSocket socket = new DatagramSocket();
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                //readLine读取输入，转换为byte放入包中发送出去
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("192.168.119.1", 8607));
                socket.send(packet);
                if (data.equals("bye")){
                    break;
                }
            }
            socket.close();
        }


    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8080);
        while (true) {
            byte[] bytes = new byte[1024];
            //接收数据读取并输出
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
            //阻塞接收
            socket.receive(packet);
            byte[] data = packet.getData();
            String result = new String(data, 0, data.length);
            System.out.println(result);
            if (result.equals("bye")) {
                break;
            }
        }
        //凡事不要忘了关闭
        socket.close();
    }

    @Test
    public void mainA() throws IOException, InterruptedException {
        String s = "FEE0A78B1211000012000C00850000D601AA02000000640001000000";

    }


    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String bytesToHexString(byte[] src,int len){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || len <= 0) {
            return null;
        }
        for (int i = 0; i < len; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
